<template>
  <view class="maintenance-container">
    <!-- 房东信息 -->
    <view class="info-section">
      <view class="section-title">
        <view class="title-bar"></view>
        <text class="section-title-text">房东信息</text>
      </view>
      <view class="input-item">
        <text class="required">*</text>
        <text class="label">姓名</text>
        <text>{{ '***' || '请直接选择地址' }}</text>
      </view>
      <view class="input-item">
        <text class="required">*</text>
        <text class="label">联系电话</text>
        <text>{{ maskPhone(formData.phone) || '请直接选择地址' }}</text>
      </view>
      <view class="tip-text">我们将以此电话号码作为联系你的方式。</view>
    </view>

    <!-- 多表单块：每个地址为一整块完整表单 -->
    <view v-for="(item, idx) in formData.addressList" :key="idx" class="info-section">
      <view class="section-title">
        <view class="title-bar"></view>
        <text class="section-title-text">缴费地址{{ idx + 1 }}</text>
        <text class="close-icon" v-if="formData.addressList.length > 1" @click="removeAddress(idx)">×</text>
      </view>
      <!-- 选择地址弹窗入口 -->
      <view class="input-item arrow-item">
        <text class="label required">选择地址</text>
        <view class="right-content">
          <view class="address-ellipsis" @click="openAddressPicker(idx)" @longpress="showFullAddress(item.fullAddress)">
            <text class="placeholder" v-if="!item.fullAddress">请选择省市区镇村/门牌</text>
            <text v-else>{{ item.fullAddress }}</text>
          </view>
          <text class="edit-btn" @click="openAddressPicker(idx)">编辑</text>
        </view>
      </view>
      <!-- 回显门禁编码 -->
      <view v-if="item.doorCode" class="input-item">
        <text class="label">门禁编码</text>
        <text>{{ item.doorCode }}</text>
      </view>
      <!-- 月数横向选择、优惠、金额等UI保持原样 -->
      <view class="maintenance-info">
        <view class="sub-title">缴费信息</view>
        <view class="month-select-section">
          <text class="month-label">连交月数</text>
          <view class="month-value">
            <input 
              class="month-input" 
              type="number" 
              v-model="item.months" 
              placeholder="请输入月数"
              @input="onMonthChange(idx, $event)"
              min="1"
              max="99"
            />
            <text class="month-unit">个月</text>
          </view>
        </view>
        <view class="month-options">
          <view class="month-btn" :class="{ active: item.months === 3 }" @click="setMonths(idx, 3)">
            <view class="recommend-tag" v-if="hasDiscountForMonths(item, 3)">惠</view>
            <text>3个月</text>
          </view>
          <view class="month-btn" :class="{ active: item.months === 6 }" @click="setMonths(idx, 6)">
            <view class="recommend-tag" v-if="hasDiscountForMonths(item, 6)">惠</view>
            <text>6个月</text>
          </view>
          <view class="month-btn" :class="{ active: item.months === 12 }" @click="setMonths(idx, 12)">
            <view class="recommend-tag" v-if="hasDiscountForMonths(item, 12)">惠</view>
            <text>12个月</text>
          </view>
        </view>
        <view class="coupon-section">
          <view class="coupon-info">
            <view class="coupon-icon">
              <text class="iconfont icon-info"></text>
            </view>
            <text class="coupon-text">
              优惠信息：
              <template v-if="hasAnyDiscountInfo(item)">
                <template v-if="item.couponInfo && item.couponInfo.ruleList && item.couponInfo.ruleList.length">
                  <text v-for="rule in item.couponInfo.ruleList" :key="rule.id">{{ rule.remark }}；</text>
                </template>
                <template v-if="item.couponInfo && item.couponInfo.giftMonthOfByOneYear && item.couponInfo.giftMonthOfByOneYear > 0">
                  <text>购买一年赠{{ item.couponInfo.giftMonthOfByOneYear }}个月；</text>
                </template>
                <template v-if="item.couponInfo && item.couponInfo.installPrice && item.couponInfo.installPrice > 0">
                  <text>安装费¥{{ Number(item.couponInfo.installPrice).toFixed(2) }}；</text>
                </template>
              </template>
              <template v-else>
                暂无优惠
              </template>
            </text>
          </view>
          <view class="coupon-action" @click="viewCoupon(idx)">
            <text class="view-coupon">查看优惠</text>
            <text class="arrow">›</text>
          </view>
        </view>
      </view>
      <view class="rate-section">
        <text class="rate-label">运维费档位</text>
        <view class="rate-options">
          <!-- 如果已有运维费档位，直接显示 -->
          <view v-if="item.rate && item.rate > 0" class="rate-option active">
            <text class="rate-unit">元/月</text>
            <view class="rate-amount-wrap">
              <text class="rate-amount">{{ item.rate }}</text>
              <text class="rate-selected">✔</text>
            </view>
          </view>
          <!-- 如果没有运维费档位，显示从优惠信息中获取的选项 -->
          <view
            v-else
            v-for="rate in (item.couponInfo && item.couponInfo.priceList ? item.couponInfo.priceList.filter(p => p.type === '1') : [])"
            :key="rate.id" class="rate-option" :class="{ active: item.rateId === rate.id }" @click="setRate(idx, rate)">
            <text class="rate-unit">元/月</text>
            <view class="rate-amount-wrap">
              <text class="rate-amount">{{ rate.price }}</text>
              <text class="rate-selected" v-if="item.rateId === rate.id">✔</text>
            </view>
          </view>
        </view>
      </view>
      <view v-if="item.noAddress" class="no-address-tip">
        未找到您的地址？请拨打客服电话：<text class="phone">400-xxxx-xxxx</text>
      </view>
    </view>
    <view class="add-address-btn" @click="addAddress">
      <text class="add-icon">+</text>
      <text>添加新地址</text>
    </view>

    <!-- 底部结算 -->
    <view class="footer">
      <view class="total-section">
        <text class="total-label">合计 {{ formData.addressList.length }}个地址
          <span v-if="formData.addressList.length > 1">
            <!-- <text class="tip-icon">ℹ</text> -->
            <span class="tip-text">(多个地址仅支持微信支付)</span>
          </span>
        </text>
        <view class="total-amount-row">
          <text class="total-price">{{ totalPrice }}</text>
          <text class="total-unit">元</text>
        </view>
      </view>
      <view class="confirm-btn" @click="confirmPayment">
        <text v-if="formData.addressList.length > 1">微信支付</text>
        <text v-else>立即支付</text>
      </view>
    </view>
    <!-- 多个地址时显示提示，放到合计后面 -->


    <uni-popup ref="addressPopup" type="bottom">
      <view class="wx-popup-content">
        <!-- 全局Loading遮罩 -->
        <view v-if="globalLoading" class="global-loading-mask">
          <view class="global-loading-container">
            <view class="global-loading-spinner"></view>
            <text class="global-loading-text">正在加载...</text>
          </view>
        </view>
                  <view class="wx-popup-tabs">
            <view :class="['wx-tab', popupTab === 0 ? 'active' : '']" @click="switchPopupTab(0)">地址选择</view>
            <view :class="['wx-tab', popupTab === 1 ? 'active' : '']" @click="switchPopupTab(1)">房东选择</view>
          </view>
        <view v-if="popupTab === 0">
          <view class="wx-popup-header">
            <view v-if="deptPath.length > 0" class="wx-back-btn" @click="goBackDept"><text
                class="wx-back-arrow">←</text>
            </view>
            <view class="wx-breadcrumb">
              <text v-for="(item, idx) in deptPath" :key="item.id" class="wx-breadcrumb-item" @click="goToDept(idx)">{{
                item.label }}</text>
            </view>
          </view>
          <view class="wx-popup-title">选择地址</view>
          <view class="wx-list-wrap">
            <view v-for="item in filteredDeptList" :key="item.id" class="wx-list-item"
              :class="{ active: isDeptActive(item) }" @click="onDeptSelect(item)">
              <text>{{ highlightKeyword(item.label, searchKeyword) }}</text>
              <text v-if="item.children && item.children.length" class="wx-arrow">›</text>
            </view>
          </view>
          <view v-if="showHouseList || filteredHouseList.length > 0">
            <view class="wx-popup-title-sub wx-blue-bar">房产地址</view>
            <!-- 添加房产地址搜索框 -->
            <view class="wx-search-input">
              <view class="search-input-wrapper">
                <uni-icons type="search" size="16" color="#999"></uni-icons>
                <input class="house-search-input" v-model="houseSearchKeyword" placeholder="请输入业主姓名、门禁编码等关键词搜索"
                  @input="onHouseSearchInput" @focus="onHouseSearchFocus" @blur="onHouseSearchBlur" />
                <text v-if="houseSearchKeyword" class="clear-btn" @click="clearHouseSearch">×</text>
              </view>
            </view>
            <view class="wx-list-wrap">
              <view v-for="house in filteredHouseList" :key="house.id" class="wx-list-item"
                @click="onHouseSelect(house)">
                <text class="wx-address-text">{{ getFullDeptNameByIds(house) }}/{{ house.address }}</text>
              </view>
            </view>
            <view v-if="!globalLoading && filteredHouseList.length === 0" class="no-address-tip">
              <view class="no-address-content">
                <uni-icons type="info" size="16" color="#ff6b6b"></uni-icons>
                <text class="no-address-text">未找到您的地址？</text>
              </view>
              <view class="contact-info">
                <text class="contact-label">请拨打客服电话：</text>
                <text class="phone-number" @click="callService">4006983338</text>
              </view>
            </view>
          </view>
        </view>
        <view v-else>
          <view class="wx-popup-title">房东选择</view>
          <view class="wx-landlord-switch">
            <uni-easyinput v-model="landlordSearch" placeholder="输入姓名/联系电话搜索" @input="onLandlordInput"
              @change="onLandlordInput" :clearable="true" />
          </view>
          <view class="wx-list-wrap">
            <view v-if="landlordSearchLoading" class="wx-search-tip">
              正在搜索房东...
            </view>
            <view v-else-if="!landlordSearch && !hasSearched" class="wx-search-tip">
              请输入房东姓名或联系电话进行搜索
            </view>
            <view v-else-if="landlordSearch && hasSearched && filteredLandlords.length === 0" class="wx-search-tip">
              未找到匹配的房东，请尝试其他关键词
            </view>
            <view v-for="landlord in filteredLandlords" :key="landlord.userId" class="wx-list-item"
              @click="onLandlordSelect(landlord)">
              <text>{{ maskName(landlord.nickName) }}（{{ maskPhone(landlord.phonenumber) }}）</text>
            </view>
          </view>
          <view v-if="showHouseList">
            <view class="wx-popup-title-sub wx-blue-bar">房产地址</view>
            <view class="wx-search-input">
              <view class="search-input-wrapper">
                <uni-icons type="search" size="16" color="#999"></uni-icons>
                <input class="house-search-input" v-model="houseSearchKeyword" placeholder="请输入业主姓名、门禁编码等关键词搜索"
                  @input="onHouseSearchInput" @focus="onHouseSearchFocus" @blur="onHouseSearchBlur" />
                <text v-if="houseSearchKeyword" class="clear-btn" @click="clearHouseSearch">×</text>
              </view>
            </view>
            <view class="wx-list-wrap">
              <view v-for="house in filteredHouseList" :key="house.id" class="wx-list-item"
                @click="onHouseSelect(house)">
                <text class="wx-address-text">{{ getFullDeptNameByIds(house) }}/{{ house.address }}</text>
              </view>
            </view>
            <view v-if="!globalLoading && filteredHouseList.length === 0" class="no-address-tip">
              <view class="no-address-content">
                <uni-icons type="info" size="16" color="#ff6b6b"></uni-icons>
                <text class="no-address-text">未找到房产地址</text>
              </view>
              <view class="contact-info">
                <text class="contact-label">请拨打客服电话：</text>
                <text class="phone-number" @click="callService">4006983338</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </uni-popup>

    <uni-popup ref="paySuccessPopup" type="center" v-model="showPaySuccess" :mask-click="false">
      <view class="pay-success-popup">
        <view class="pay-success-icon"></view>
        <view class="pay-success-title">支付成功</view>
        <view class="pay-success-desc">请到公众号查看消息</view>
        <button class="pay-success-btn" @click="closePaySuccess">我知道了</button>
      </view>
    </uni-popup>

    <uni-popup ref="autoRenewPopup" type="center">
      <view class="auto-renew-popup">
        <view class="title">开通自动续费服务？</view>
        <view class="desc">
          开通后，系统将在服务到期前自动为您扣款续费，保障服务不中断。<br>
          您可随时在"我的-设置"中关闭自动续费。
        </view>
        <view class="btn-group">
          <button class="cancel" @click="onSelectAutoRenew(false)">微信支付</button>
          <button class="primary" @click="onSelectAutoRenew(true)">银行卡自动扣费</button>
        </view>
      </view>
    </uni-popup>
    
    <!-- 新增优惠信息弹窗 -->
    <uni-popup ref="couponPopup" type="center">
      <view class="coupon-detail-popup">
        <view class="popup-header">
          <text class="popup-title">优惠详情</text>
          <text class="close-icon" @click="$refs.couponPopup.close()">×</text>
        </view>
        <view class="coupon-content">
          <view v-if="currentCouponInfo">
            <!-- 价格信息 -->
            <view v-if="currentCouponInfo.installPrice || currentCouponInfo.giftMonthOfByOneYear" class="price-info-section">
              <view class="section-title">
                <text class="section-icon">💰</text>
                <text class="section-text">价格信息</text>
              </view>
              <view v-if="currentCouponInfo.installPrice && currentCouponInfo.installPrice > 0" class="info-item">
                <text class="info-label">安装费</text>
                <text class="info-value">¥{{ Number(currentCouponInfo.installPrice).toFixed(2) }}</text>
              </view>
              <view v-if="currentCouponInfo.giftMonthOfByOneYear && currentCouponInfo.giftMonthOfByOneYear > 0" class="info-item">
                <text class="info-label">购买一年优惠</text>
                <text class="info-value highlight">赠送{{ currentCouponInfo.giftMonthOfByOneYear }}个月</text>
              </view>
            </view>

            <!-- 优惠规则 -->
            <view v-if="currentCouponInfo.ruleList && currentCouponInfo.ruleList.length" class="rules-section">
              <view class="section-title">
                <text class="section-icon">🎁</text>
                <text class="section-text">优惠规则</text>
              </view>
              <view v-for="rule in currentCouponInfo.ruleList" :key="rule.id" class="coupon-rule-item">
                <view class="rule-header">
                  <text class="rule-tag">优惠</text>
                  <text class="rule-title">{{ rule.remark }}</text>
                </view>
                <view v-if="rule.buyMonth || rule.freeMonth" class="rule-details">
                  <text v-if="rule.buyMonth" class="rule-detail">购买：{{ rule.buyMonth }}个月</text>
                  <text v-if="rule.freeMonth" class="rule-detail">赠送：{{ rule.freeMonth }}个月</text>
                </view>
                <view v-if="rule.description" class="rule-description">
                  <text>{{ rule.description }}</text>
                </view>
              </view>
            </view>

            <!-- 运维费档位 -->
            <view v-if="currentCouponInfo.priceList && currentCouponInfo.priceList.length" class="price-list-section">
              <view class="section-title">
                <text class="section-icon">📋</text>
                <text class="section-text">运维费档位</text>
              </view>
              <view v-for="price in currentCouponInfo.priceList.filter(p => p.type === '1')" :key="price.id" class="price-item">
                <text class="price-label">{{ price.name || '标准档位' }}</text>
                <text class="price-amount">¥{{ Number(price.price).toFixed(2) }}/月</text>
              </view>
            </view>

            <!-- 说明信息 -->
            <view v-if="currentCouponInfo.instruction" class="instruction-section">
              <view class="section-title">
                <text class="section-icon">ℹ️</text>
                <text class="section-text">说明</text>
              </view>
              <text class="instruction-text">{{ currentCouponInfo.instruction }}</text>
            </view>
          </view>
          <view v-else class="no-coupon">
            <text class="no-coupon-icon">📭</text>
            <text class="no-coupon-text">暂无优惠信息</text>
          </view>
        </view>
      </view>
    </uni-popup>

    <!-- 新增银行卡列表弹窗 -->
    <uni-popup ref="bankCardPopup" type="center">
      <view class="bank-card-popup">
        <view class="popup-header">
          <text class="popup-title">选择支付银行卡</text>
          <text class="close-icon" @click="$refs.bankCardPopup.close()">×</text>
        </view>
        <view class="bank-card-content">
          <view v-if="cardList.length === 0" class="no-card-tip">
            <text>暂无绑定的银行卡</text>
            <button class="bind-card-btn" @click="goBindCard">去绑定</button>
          </view>
          <view v-else class="card-list">
            <view v-for="(card, index) in cardList" :key="card.chCardNo" 
              class="card-item" 
              :class="{ active: selectedCardIndex === index }"
              @click="selectCard(index)">
              <view class="card-info">
                <view class="bank-name">{{ card.bankName }}</view>
                <view class="card-no">{{ maskCardNo(card.chCardNo) }}</view>
              </view>
              <view class="card-selected" v-if="selectedCardIndex === index">✓</view>
            </view>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import request from '@/utils/request';
import { getCardList, singlePay, addOrderInfo, getDeptTree, getLandlordList, getHouseList, getDeptPrice, getHouseDetailByLandlord } from '@/api/login';
export default {
  components: {
    uniIcons: () => import('@/uni_modules/uni-icons/components/uni-icons/uni-icons')
  },
  data() {
    return {
      formData: {
        name: '',
        phone: '',
        addressList: [
          {
            province: '', city: '', district: '', street: '', village: '', addressId: '', fullAddress: '', noAddress: false, months: ''
          }
        ],
        // 其它业务字段如plan、engineeringFee等可按需添加
      },
      deptTree: [],
      deptPath: [],
      currentDeptList: [],
      searchKeyword: '',
      filteredDeptList: [],
      showHouseList: false,
      houseList: [],
      houseSearchKeyword: '',
      filteredHouseList: [],
      addressPickerIdx: 0,
      popupTab: 0,
      landlordSearch: '',
      filteredLandlords: [],
      allLandlords: [],
      landlordId: '',
      isPaying: false,
      showPaySuccess: false,
      paySuccessOrderId: '',
      isAutoRenew: false,
      autoRenewPaying: false,
      openid: '',
      globalLoading: false, // 全局loading状态
      currentCouponInfo: null, // 新增当前查看的优惠信息
      // 新增搜索相关状态
      landlordSearchLoading: false,
      landlordSearchDebounceTimer: null,
      hasSearched: false,
      cardList: [],
      selectedCardIndex: null
    }
  },
  mounted() {
    this.getDeptTree();
    // 自动读取上次缓存
    const cache = uni.getStorageSync('maintenanceFormData');
    if (cache) {
      try {
        const parsed = typeof cache === 'string' ? JSON.parse(cache) : cache;
        if (parsed && parsed.name) {
          this.formData = Object.assign(this.formData, parsed);
        }
      } catch (e) { }
    }
    // 检查是否绑卡后返回自动发起协议支付
    const autoRenewBack = uni.getStorageSync('autoRenewBack');
    if (autoRenewBack) {
      uni.removeStorageSync('autoRenewBack');
      this.handleAutoRenewPay();
    }
  },
  watch: {
    formData: {
      handler(val) {
        uni.setStorageSync('maintenanceFormData', JSON.stringify(val));
      },
      deep: true
    }
  },
  methods: {
    addAddress() {
      this.formData.addressList.push({ province: '', city: '', district: '', street: '', village: '', addressId: '', fullAddress: '', noAddress: false, months: '' });
      this.$nextTick(() => {
        this.openAddressPicker(this.formData.addressList.length - 1);
      });
    },
    removeAddress(idx) {
      this.formData.addressList.splice(idx, 1);
    },
    // 新增：切换弹窗Tab时需要清空landlordId并重置列表
    switchPopupTab(tabIndex) {
      this.popupTab = tabIndex;
      // 清空已选房东，避免交叉筛选影响
      this.landlordId = '';
      if (tabIndex === 0) {
        // 切到地址选择
        this.landlordSearch = '';
        this.filteredLandlords = [];
        this.hasSearched = false;
        // 清空层级路径与当前层级列表
        this.deptPath = [];
        this.currentDeptList = this.deptTree.length ? (this.deptTree[0].children || []) : [];
        this.filteredDeptList = this.currentDeptList;
        this.searchKeyword = '';
        // 仅清空来源于房东选择的地址项，来源于地址选择的保留
        if (Array.isArray(this.formData.addressList)) {
          this.formData.addressList.forEach((cur, i) => {
            if (cur && cur.selectedSource === 'landlord') {
              const cleared = {
                ...cur,
                addressId: '',
                fullAddress: '',
                province: '',
                city: '',
                district: '',
                street: '',
                village: '',
                townName: '',
                townId: '',
                villageName: '',
                villageId: '',
                address: '',
                door: '',
                doorCode: '',
                couponInfo: null,
                rateId: '',
                rate: '',
                rateInfo: undefined,
                months: '',
                noAddress: false,
                selectedSource: ''
              };
              this.$set(this.formData.addressList, i, cleared);
            }
          });
        }
        // 清除可能的本地缓存的房产资料
        try { uni.removeStorageSync('maintenanceHouseDetail'); } catch (e) {}
      } else if (tabIndex === 1) {
        // 切到房东选择，重置地址列表展示
        this.searchKeyword = '';
        this.houseSearchKeyword = '';
        this.showHouseList = false;
        this.currentDeptList = this.deptTree.length ? this.deptTree[0].children : [];
        this.filteredDeptList = this.currentDeptList;
        this.filteredHouseList = [];
        // 清空房东搜索状态
        this.filteredLandlords = [];
        this.hasSearched = false;
        this.landlordSearchLoading = false;
      }
    },
    async openAddressPicker(idx) {
      this.addressPickerIdx = idx;
      this.deptPath = [];
      this.searchKeyword = '';
      this.houseSearchKeyword = '';
      this.landlordSearch = '';
      this.showHouseList = false;
      this.currentDeptList = this.deptTree.length ? this.deptTree[0].children : [];
      this.filteredDeptList = this.currentDeptList;
      
      // 清空房东相关状态
      this.filteredLandlords = [];
      this.hasSearched = false;
      this.landlordSearchLoading = false;
      
      this.popupTab = 0;
      this.$refs.addressPopup.open();
    },
    closeAddressPopup() {
      this.$refs.addressPopup.close();
      // 关闭弹窗时同步清空地址层级路径，避免下次进入保留历史路径
      this.deptPath = [];
    },
    goBackDept() {
      if (this.deptPath.length > 0) {
        this.deptPath.pop();
        if (this.deptPath.length === 0) {
          // 回到根级别
          this.currentDeptList = this.deptTree.length ? this.deptTree[0].children : [];
          this.filteredDeptList = this.currentDeptList;
          this.showHouseList = false;
        } else {
          // 回到上一级
          const lastDept = this.deptPath[this.deptPath.length - 1];
          if (lastDept.children && lastDept.children.length > 0) {
            // 有子节点，显示子节点列表
            this.currentDeptList = lastDept.children;
            this.filteredDeptList = this.currentDeptList;
            this.showHouseList = false;
          } else {
            // 叶子节点，保持当前列表显示，并获取房产列表
            this.showHouseList = true;
            this.fetchHouseList(lastDept.id);
          }
        }
        this.searchKeyword = '';
      }
    },
    goToDept(idx) {
      this.deptPath = this.deptPath.slice(0, idx + 1);
      if (this.deptPath.length > 0) {
        const targetDept = this.deptPath[idx];
        if (targetDept.children && targetDept.children.length > 0) {
          // 有子节点，显示子节点列表
          this.currentDeptList = targetDept.children;
          this.filteredDeptList = this.currentDeptList;
          this.showHouseList = false;
        } else {
          // 叶子节点，保持当前列表显示，并获取房产列表
          this.showHouseList = true;
          this.fetchHouseList(targetDept.id);
        }
      } else {
        this.currentDeptList = this.deptTree.length ? this.deptTree[0].children : [];
        this.filteredDeptList = this.currentDeptList;
        this.showHouseList = false;
      }
      this.searchKeyword = '';
    },
    isDeptActive(item) {
      // 简单直接的判断：检查当前项是否在路径中
      const isActive = this.deptPath.some(dept => dept.id === item.id);
      console.log('检查选中状态:', item.label, 'ID:', item.id, '是否选中:', isActive, '路径:', this.deptPath.map(d => d.label));
      return isActive;
    },
    onDeptSelect(item) {
      console.log('选择部门:', item.label, 'ID:', item.id);
      
      if (item.children && item.children.length > 0) {
        // 有子节点，进入下一级
        console.log('进入下一级:', item.children.length, '个子节点');
        this.deptPath.push(item);
        this.currentDeptList = item.children;
        this.filteredDeptList = item.children;
        this.searchKeyword = '';
        this.showHouseList = false;
      } else {
        // 叶子节点，选择村
        console.log('选择叶子节点:', item.label);
        
        // 构建新的路径，确保路径中只有一个叶子节点
        const newPath = [];
        
        // 复制所有有子节点的路径
        for (let i = 0; i < this.deptPath.length; i++) {
          const dept = this.deptPath[i];
          if (dept.children && dept.children.length > 0) {
            newPath.push(dept);
          }
        }
        
        // 添加当前选中的叶子节点
        newPath.push(item);
        
        // 一次性更新所有状态
        this.deptPath = newPath;
        // 保持当前列表显示，不清空村列表
        // this.currentDeptList = []; // 不清空，保持村列表显示
        // this.filteredDeptList = []; // 不清空，保持村列表显示
        this.searchKeyword = '';
        
        // 获取房产列表并显示
        this.fetchHouseList(item.id);
      }
    },
    onSearchInput() {
      if (!this.searchKeyword) {
        this.filteredDeptList = this.currentDeptList;
      } else {
        this.filteredDeptList = this.recursiveFilter(this.currentDeptList, this.searchKeyword);
      }
    },
    recursiveFilter(list, keyword) {
      const res = [];
      for (const item of list) {
        if (item.label.includes(keyword)) {
          res.push(item);
        } else if (item.children && item.children.length) {
          const children = this.recursiveFilter(item.children, keyword);
          if (children.length) {
            res.push({ ...item, children });
          }
        }
      }
      return res;
    },
    highlightKeyword(label, keyword) {
      if (!keyword) return label;
      return label.replace(new RegExp(keyword, 'g'), `<span style="color:#07c160">${keyword}</span>`);
    },
    async fetchHouseList(deptId) {
      this.globalLoading = true; // 开始全局加载
      try {
        const res = await getHouseList({ pageNum: 1, pageSize: 1000000000, deptId });
        if (res.code === 200 && res.rows) {
          this.houseList = res.rows;
          this.filteredHouseList = this.houseList;
          this.showHouseList = true; // 显示房产列表
          // 新增：自动填充第一个房东信息
          if (res.rows.length > 0) {
            const first = res.rows[0];
            if (first.landlordName) this.formData.name = first.landlordName;
            if (first.landlordPhone) this.formData.phone = first.landlordPhone;
          }
        } else {
          this.houseList = [];
          this.filteredHouseList = [];
          this.showHouseList = true; // 即使没有数据也要显示列表区域
        }
      } catch (e) {
        this.houseList = [];
        this.filteredHouseList = [];
        this.showHouseList = true; // 出错时也要显示列表区域
      } finally {
        this.globalLoading = false; // 结束全局加载
      }
    },
    // 处理房产地址搜索
    onHouseSearchInput(e) {
      // 处理输入事件，e可能是事件对象或直接的值
      let input = '';
      if (typeof e === 'string') {
        input = e;
      } else if (e && e.detail && e.detail.value !== undefined) {
        input = e.detail.value;
      } else if (e && e.target && e.target.value !== undefined) {
        input = e.target.value;
      } else {
        input = e || '';
      }
      
      const keyword = input.trim();
      if (!keyword) {
        this.filteredHouseList = this.houseList;
      } else {
        this.filteredHouseList = this.houseList.filter(house => {
          // 搜索地址和门禁编码
          const fullAddress = this.getFullDeptNameByIds(house) + '/' + house.address + house.door;
          console.log(fullAddress)
          return fullAddress.toLowerCase().includes(keyword.toLowerCase());
        });
      }
    },
    
    // 房产搜索框获得焦点
    onHouseSearchFocus() {
      // 可以在这里添加搜索框获得焦点时的逻辑
    },

    // 房产搜索框失去焦点
    onHouseSearchBlur() {
      // 可以在这里添加搜索框失去焦点时的逻辑
    },

    // 清空房产搜索
    clearHouseSearch() {
      this.houseSearchKeyword = '';
      this.filteredHouseList = this.houseList;
      console.log('清空搜索，显示全部房产:', this.houseList.length, '条');
    },
    getTownIdFromHouse(house) {
      // 优先级：street > town > district
      // 兼容不同数据结构
      if (house.street) return house.street;
      if (house.townId) return house.townId;
      if (house.town) return house.town;
      // 兜底
      return '';
    },
    async onHouseSelect(house) {
      const fullAddress = this.getFullDeptNameByIds(house) + '/' + house.address;
      const idx = this.addressPickerIdx;
      const newItem = {
        ...this.formData.addressList[idx],
        addressId: house.id,
        fullAddress,
        door: house.door,
        province: house.province,
        city: house.city,
        district: house.district,
        street: house.street,
        village: house.village,
        noAddress: false
      };
      // 获取镇街id
      const townId = this.getTownIdFromHouse(house);
      // 查询优惠信息
      newItem.couponInfo = townId ? await this.fetchCouponInfo(townId) : null;
      this.$set(this.formData.addressList, idx, newItem);
      
      // 新增：赋值房东信息
      if (house.landlordName) this.formData.name = house.landlordName;
      if (house.landlordPhone) this.formData.phone = house.landlordPhone;
      
      // 如果房产数据中有monthPrice，直接设置运维费档位
      if (house.monthPrice && house.monthPrice > 0) {
        newItem.rateId = 'default';
        newItem.rate = house.monthPrice;
        newItem.rateInfo = {
          id: 'default',
          price: house.monthPrice,
          type: '1'
        };
        this.$set(this.formData.addressList, idx, newItem);
        console.log('从房产数据设置运维费档位:', house.monthPrice);
      }
      
      // 根据房东姓名查询房产资料，获取门禁编码和地址信息
      await this.fetchHouseDetailByLandlord(house);
      
      this.closeAddressPopup();
    },
    async fetchCouponInfo(deptId) {
      try {
        const res = await getDeptPrice(deptId);
        if (res.code === 200 && res.data) {
          const data = res.data || {};
          if (Array.isArray(data.ruleList)) {
            data.ruleList = data.ruleList.map(r => ({ ...r, remark: this.buildRuleRemark(r) }));
          }
          return data;
        }
      } catch (e) { }
      return null;
    },
    
    // 根据优惠规则生成展示文案
    buildRuleRemark(rule) {
      const b = Number(rule && rule.buyMonth);
      const f = Number(rule && rule.freeMonth);
      if (b > 0 && f > 0) return `买${b}送${f}`;
      if (b > 0 && (!f || f === 0)) return `购买${b}个月优惠`;
      return '优惠活动';
    },
    // 是否存在与指定月份匹配的优惠（用于显示"惠"标签）
    hasDiscountForMonths(item, months) {
      const rules = item && item.couponInfo && Array.isArray(item.couponInfo.ruleList) ? item.couponInfo.ruleList : [];
      return rules.some(r => Number(r.buyMonth) === Number(months) && Number(r.freeMonth) > 0);
    },
    // 判断是否有任何优惠信息
    hasAnyDiscountInfo(item) {
      if (!item || !item.couponInfo) return false;
      const couponInfo = item.couponInfo;
      
      // 检查是否有优惠规则
      const hasRules = couponInfo.ruleList && couponInfo.ruleList.length > 0;
      
      // 检查是否有购买一年赠送月数
      const hasGiftMonths = couponInfo.giftMonthOfByOneYear && couponInfo.giftMonthOfByOneYear > 0;
      
      // 检查是否有安装费信息
      const hasInstallPrice = couponInfo.installPrice && couponInfo.installPrice > 0;
      
      // 检查是否有运维费档位
      const hasPriceList = couponInfo.priceList && couponInfo.priceList.length > 0;
      
      // 检查是否有说明信息
      const hasInstruction = couponInfo.instruction && couponInfo.instruction.trim().length > 0;
      
      return hasRules || hasGiftMonths || hasInstallPrice || hasPriceList || hasInstruction;
    },
    // 根据房东姓名查询房产资料
    async fetchHouseDetailByLandlord(house) {
      try {
        if (!house.landlordName || !house.village) {
          console.log('缺少房东姓名或村信息，跳过房产资料查询');
          return;
        }
        
        const params = {
          pageNum: 1,
          pageSize: 10,
          deptId: house.village, // 使用村级ID作为deptId
          village: house.village,
          jzxm: house.landlordName // 房东姓名
        };
        
        console.log('查询房产资料参数:', params);
        console.log('选择的房产信息:', {
          address: house.address,
          door: house.door,
          landlordName: house.landlordName,
          fullAddress: house.fullAddress
        });
        
        const res = await getHouseDetailByLandlord(params);
        console.log('房产资料查询结果:', res);
        
        if (res.code === 200 && res.rows && res.rows.length > 0) {
          console.log('接口返回的所有房产数据:', res.rows.map(item => ({
            address: item.address,
            mjbm: item.mjbm,
            monthPrice: item.monthPrice,
            jzxm: item.jzxm
          })));
          
          // 根据选择的地址匹配正确的房产数据
          let houseDetail = null;
          let matchMethod = '';
          
          // 优先匹配地址和门禁编码
          if (house.address && house.door) {
            houseDetail = res.rows.find(item => 
              item.address === house.address && item.mjbm === house.door
            );
            if (houseDetail) matchMethod = '地址+门禁编码匹配';
          }
          
          // 如果没找到，尝试只匹配地址
          if (!houseDetail && house.address) {
            houseDetail = res.rows.find(item => item.address === house.address);
            if (houseDetail) matchMethod = '地址匹配';
          }
          
          // 如果还没找到，尝试匹配门禁编码
          if (!houseDetail && house.door) {
            houseDetail = res.rows.find(item => item.mjbm === house.door);
            if (houseDetail) matchMethod = '门禁编码匹配';
          }
          
          // 最后兜底取第一个结果
          if (!houseDetail) {
            houseDetail = res.rows[0];
            matchMethod = '兜底使用第一条数据';
            console.log('未找到精确匹配的房产数据，使用第一条数据作为兜底');
          }
          
          console.log(`匹配方式: ${matchMethod}, 匹配到的房产数据:`, {
            address: houseDetail.address,
            mjbm: houseDetail.mjbm,
            monthPrice: houseDetail.monthPrice,
            jzxm: houseDetail.jzxm
          });
          
          // 存储到localStorage，包含address和mjbm
          const houseInfo = {
            address: houseDetail.address || '',
            mjbm: houseDetail.mjbm || '',
            landlordName: houseDetail.landlordName || houseDetail.jzxm || '',
            landlordPhone: houseDetail.landlordPhone || houseDetail.zjlxdh || '',
            fullAddress: house.fullAddress || '', // 保留原来的完整地址
            // 其他可能有用的信息
            htbh: houseDetail.htbh || '',
            sfzh: houseDetail.sfzh || '',
            kdzh: houseDetail.kdzh || '',
            kdmm: houseDetail.kdmm || '',
            monthPrice: houseDetail.monthPrice || 0 // 添加运维费档位
          };
          
          // 存储到localStorage
          uni.setStorageSync('maintenanceHouseDetail', JSON.stringify(houseInfo));
          console.log('房产资料已存储到localStorage:', houseInfo);
          
          // 设置运维费档位到当前地址项
          const idx = this.addressPickerIdx;
          if (this.formData.addressList[idx]) {
            this.$set(this.formData.addressList[idx], 'rateId', 'default');
            this.$set(this.formData.addressList[idx], 'rate', houseDetail.monthPrice || 0);
            this.$set(this.formData.addressList[idx], 'rateInfo', {
              id: 'default',
              price: houseDetail.monthPrice || 0,
              type: '1'
            });
            console.log('已设置运维费档位:', houseDetail.monthPrice);
          }
          
        } else {
          console.log('未找到房产资料或返回数据为空');
        }
      } catch (error) {
        console.error('查询房产资料失败:', error);
      }
    },
    async getDeptTree() {
      try {
        const res = await getDeptTree();
        if (res.code === 200 && res.data && res.data.length) {
          this.deptTree = res.data;
        } else {
          this.deptTree = [];
        }
      } catch (e) {
        this.deptTree = [];
      }
    },
    async getLandlordList(searchKeyword = '') {
      this.landlordSearchLoading = true;
      try {
        // 使用合理的数据量和搜索参数
        const params = { 
          pageNum: 1, 
          pageSize: 50, // 适当减少数量
          roleId: 100
        };
        
        // 如果有搜索关键词，先按姓名搜索
        if (searchKeyword && searchKeyword.trim()) {
          params.nickName = searchKeyword.trim(); // 先按姓名搜索
        }
        
        const res = await getLandlordList(params);
        console.log('房东接口返回数据:', res);
        if (res.code === 200 && res.rows && res.rows.length > 0) {
          this.filteredLandlords = res.rows;
          this.hasSearched = true;
          console.log('姓名搜索完成，关键词:', searchKeyword, '结果数量:', res.rows.length);
        } else {
          // 姓名搜索无结果，再按手机号搜索
          if (searchKeyword && searchKeyword.trim()) {
            params.phonenumber = searchKeyword.trim();
            delete params.nickName;
            
            const phoneRes = await getLandlordList(params);
            
            if (phoneRes.code === 200 && phoneRes.rows && phoneRes.rows.length > 0) {
              this.filteredLandlords = phoneRes.rows;
              this.hasSearched = true;
              console.log('手机号搜索完成，关键词:', searchKeyword, '结果数量:', phoneRes.rows.length);
            } else {
              this.filteredLandlords = [];
              this.hasSearched = true;
              console.log('姓名和手机号均无搜索结果');
            }
          } else {
            this.filteredLandlords = [];
            this.hasSearched = true;
          }
        }
      } catch (e) {
        console.error('获取房东列表失败:', e);
        this.filteredLandlords = [];
        this.hasSearched = true;
      } finally {
        this.landlordSearchLoading = false;
      }
    },
    async onLandlordSelect(landlord) {
      console.log('选择房东:', landlord);
      this.landlordId = landlord.userId;
      this.formData.name = landlord.nickName || landlord.nickName;
      this.formData.phone = landlord.phonenumber;
      await this.fetchHouseListAllByLandlord(landlord.userId);
    },
    async fetchHouseListAllByLandlord(landlordId) {
      this.globalLoading = true; // 开始全局加载
      try {
        const res = await getHouseList({ pageNum: 1, pageSize: 1000, landlordId });
        if (res.code === 200 && res.rows) {
          this.houseList = res.rows;
          this.filteredHouseList = this.houseList;
          this.showHouseList = true;
        } else {
          this.houseList = [];
          this.filteredHouseList = [];
          this.showHouseList = true;
        }
      } catch (e) {
        this.houseList = [];
        this.filteredHouseList = [];
        this.showHouseList = true;
      } finally {
        this.globalLoading = false; // 结束全局加载
      }
    },
    getFullDeptNameByIds({ province, city, district, street, village }) {
      let names = [];
      let node = this.deptTree && this.deptTree[0];
      if (!node) return '';
      function findChild(children, id) {
        if (!children || !id) return null;
        for (let c of children) {
          if (c.id === id) return c;
        }
        return null;
      }
      let cur = node;
      if (province && cur) { cur = findChild(cur.children, province); if (cur) names.push(cur.label); }
      if (city && cur) { cur = findChild(cur.children, city); if (cur) names.push(cur.label); }
      if (district && cur) { cur = findChild(cur.children, district); if (cur) names.push(cur.label); }
      if (street && cur) { cur = findChild(cur.children, street); if (cur) names.push(cur.label); }
      if (village && cur) { cur = findChild(cur.children, village); if (cur) names.push(cur.label); }
      return names.join('/')
    },
    onLandlordInput(val) {
      // 处理输入事件，val可能是事件对象或直接的值
      let input = '';
      if (typeof val === 'string') {
        input = val;
      } else if (val && val.detail && val.detail.value !== undefined) {
        input = val.detail.value;
      } else if (val && val.target && val.target.value !== undefined) {
        input = val.target.value;
      } else {
        input = val || '';
      }
      
      input = input.trim();
      console.log('房东搜索输入:', input);
      
      // 清除之前的定时器
      if (this.landlordSearchDebounceTimer) {
        clearTimeout(this.landlordSearchDebounceTimer);
      }
      
      // 如果输入为空，清空结果
      if (!input) {
        this.filteredLandlords = [];
        this.hasSearched = false;
        this.landlordSearchLoading = false;
        return;
      }
      
      // 设置防抖定时器
      this.landlordSearchDebounceTimer = setTimeout(() => {
        this.searchLandlordByKeyword(input);
      }, 300); // 300ms 防抖
    },
    
    // 新增：根据关键词搜索房东
    async searchLandlordByKeyword(keyword) {
      if (!keyword || keyword.length < 1) {
        this.filteredLandlords = [];
        this.hasSearched = false;
        return;
      }
      
      console.log('开始搜索房东，关键词:', keyword);
      await this.getLandlordList(keyword);
    },
    maskName(name) {
      if (!name) return '';
      if (name.length === 2) return name[0] + '*';
      if (name.length > 2) return name[0] + '*'.repeat(name.length - 2) + name[name.length - 1];
      return name;
    },
    maskPhone(phone) {
      if (!phone) return '';
      // 手机号脱敏
      if (/^1[3-9]\d{9}$/.test(phone)) {
        return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
      }
      // 固定电话脱敏
      if (/^0\d{2,3}-?\d{7,8}$/.test(phone)) {
        return phone.replace(/(\d{3,4})-?(\d{3})\d{4}/, '$1****$2');
      }
      return phone;
    },
    // 验证手机号或固定电话
    isValidPhone(phone) {
      if (!phone) return false;
      
      // 手机号验证：1开头，第二位3-9，总共11位
      const mobileRegex = /^1[3-9]\d{9}$/;
      
      // 固定电话验证：
      // 1. 区号3-4位（0开头）+ 7-8位号码，可选中间的横线
      // 2. 支持格式：0755-12345678、075512345678、021-1234567、02112345678等
      const landlineRegex = /^0\d{2,3}-?\d{7,8}$/;
      
      return mobileRegex.test(phone) || landlineRegex.test(phone);
    },
    async confirmPayment() {
      if (this.isPaying) return;
      if (!this.formData.name) {
        return uni.showToast({ title: '请输入姓名', icon: 'none' });
      }
      if (!this.formData.phone) {
        return uni.showToast({ title: '请输入联系电话', icon: 'none' });
      }
      if (!this.isValidPhone(this.formData.phone)) {
        return uni.showToast({ title: '请输入正确的手机号或固定电话', icon: 'none' });
      }
      if (!this.formData.addressList.length) {
        return uni.showToast({ title: '请添加至少一个缴费地址', icon: 'none' });
      }
      for (let i = 0; i < this.formData.addressList.length; i++) {
        const addr = this.formData.addressList[i];
        if (!addr.fullAddress || !addr.addressId) {
          return uni.showToast({ title: `请完整选择第${i + 1}个地址`, icon: 'none' });
        }
        if (!addr.rateId) {
          return uni.showToast({ title: `请为第${i + 1}个地址选择运维档位`, icon: 'none' });
        }
      }

      // 多个地址时只能微信支付，不显示自动续费弹窗
      if (this.formData.addressList.length > 1) {
        await this.handleWechatPay();
        return;
      }

      // 单个地址时显示自动续费选择弹窗
      this.$refs.autoRenewPopup.open();
    },
    async onSelectAutoRenew(isAutoRenew) {
      if (!isAutoRenew) {
        // 暂不开通自动续费，直接微信支付
        await this.handleWechatPay();
        return;
      }
      try {
        // 1. 查询绑定的银行卡
        const userId = uni.getStorageSync('userId');
        const res = await getCardList({ userId });
        if (!res || res.code !== 200 || !res.data || res.data.length === 0) {
          uni.showToast({ title: '请先绑定银行卡', icon: 'none' });
          // 跳转
          uni.navigateTo({
            url: '/pages/mine/bindCard/index'
          });
          return;
        }
        // 显示银行卡列表
        this.cardList = res.data.map(card => ({
          ...card,
          bankName: this.getBankNameByCardNo(card.chCardNo) // 根据卡号获取银行名称
        }));
        this.selectedCardIndex = null;
        this.$refs.bankCardPopup.open();
      } catch (e) {
        console.log(e);
        uni.showToast({ title: '获取银行卡列表失败', icon: 'none' });
      }
    },
    // 根据卡号获取银行名称
    getBankNameByCardNo(cardNo) {
      // 这里可以根据卡号规则判断银行，暂时返回"银行卡"
      if (cardNo.startsWith('621226')) return '工商银行';
      if (cardNo.startsWith('621792')) return '建设银行';
      return '银行卡';
    },
    maskCardNo(cardNo) {
      if (!cardNo) return '';
      return cardNo.replace(/^(\d{4})\d+(\d{4})$/, '$1 **** **** $2');
    },
    async selectCard(index) {
      this.selectedCardIndex = index;
      const card = this.cardList[index];
      
      try {
        // 组装订单详情列表
        const orderDetailList = this.formData.addressList.map(addr => {
          return {
            address: addr.fullAddress || '',
            buyCount: addr.months || 1,
            city: Number(addr.city) || 0,
            country: 0,
            deptId: Number(addr.street) || 0,
            district: Number(addr.district) || 0,
            door: addr.door || '',
            houseId: Number(addr.addressId) || 0,
            isPolice: '0',
            name: this.formData.name,
            phone: this.formData.phone,
            province: Number(addr.province) || 0,
            street: Number(addr.street) || 0,
            unitPrice: Number(addr.rate) || 0,
            village: Number(addr.village) || 0,
            type: 1
          };
        });

        const orderParams = {
          chCardNo: card.chCardNo,
          chIdNo: card.chIdNo,
          chMobile: card.chMobile,
          chName: card.chName,
          openid: uni.getStorageSync('wechat_openid'),
          landlordName: this.formData.name,
          landlordPhone: this.formData.phone,
          orderDetailList: orderDetailList,
          payChannel: '2',
          protocolNo: card.protocolNo,
          remark: `${this.formData.addressList.map(addr => addr.fullAddress).join('；')}`,
          type: 1
        };

        console.log('创建订单参数:', orderParams);
        const addRes = await addOrderInfo(orderParams);
        console.log('创建订单返回:', addRes);

        if (!addRes || addRes.code !== 200 || !addRes.data || !addRes.data.orderNo) {
          uni.showToast({ title: addRes.msg || '下单失败', icon: 'none' });
          return;
        }

        // 合并银行卡信息到订单对象
        const orderData = {
          ...addRes.data,
          chCardNo: card.chCardNo || '',
          chName: card.chName || '',
          chIdNo: card.chIdNo || '',
          chMobile: card.chMobile || '',
          openid: uni.getStorageSync('wechat_openid'),
          protocolNo: card.protocolNo || '',
          landlordName: this.formData.name,
          landlordPhone: this.formData.phone,
          door: this.formData.addressList[0].door
        };

        console.log('跳转参数:', orderData);
        
        // 先关闭弹窗
        this.$refs.bankCardPopup.close();
        
        // 延迟一下再跳转，确保弹窗已经完全关闭
        setTimeout(() => {
          const url = `/pages/mine/maintenance/payConfirm?data=${encodeURIComponent(JSON.stringify(orderData))}&payType=bank`;
          console.log('跳转URL:', url);
          uni.navigateTo({
            url,
            fail: (err) => {
              console.error('跳转失败:', err);
              uni.showToast({
                title: '跳转失败，请重试',
                icon: 'none'
              });
            }
          });
        }, 100);

      } catch (e) {
        console.error('支付处理失败:', e);
        uni.showToast({ title: '支付失败，请重试', icon: 'none' });
      }
    },
    isLogin() {
      // 判断是否登录
      console.log(uni.getStorageSync('App-Token'))
      return !!uni.getStorageSync('App-Token');
    },
    async handleWechatPay() {
      let openid = uni.getStorageSync('wechat_openid');
      if (!openid) {
        await this.getWechatOpenId();
        openid = this.openid;
      }
      this.isPaying = true;
      try {
        // 组装订单详情列表
        const orderDetailList = this.formData.addressList.map(addr => {
          return {
            address: addr.fullAddress || '',
            buyCount: addr.months || 1,
            city: Number(addr.city) || 0,
            country: 0,
            deptId: Number(addr.street) || 0,
            district: Number(addr.district) || 0,
            door: addr.door || '',
            houseId: Number(addr.addressId) || 0,
            isPolice: '0',
            name: this.formData.name,
            phone: this.formData.phone,
            province: Number(addr.province) || 0,
            street: Number(addr.street) || 0,
            unitPrice: Number(addr.rate) || 0,
            village: Number(addr.village) || 0,
            type: 1
          };
        });

        const orderParams = {
          chCardNo: '',
          chIdNo: '',
          chMobile: this.formData.phone,
          chName: this.formData.name,
          openid: uni.getStorageSync('wechat_openid'),
          orderDetailList: orderDetailList,
          payChannel: '1',
          openid: uni.getStorageSync('wechat_openid'),
          protocolNo: '',
          remark: `${this.formData.addressList.map(addr => addr.fullAddress).join('；')}`,
          type: 1
        };
        // 新增订单（用api/login中的addOrder）
        const addRes = await addOrderInfo(orderParams);
        if (!addRes || addRes.code !== 200 || !addRes.data || !addRes.data.orderNo) {
          uni.showToast({ title: addRes.msg || '下单失败', icon: 'none' });
          return;
        }
        const orderInfo = '番禺设备门禁升级缴费';
        const amount = this.totalPrice;
        const orderNo = addRes.data.orderNo;
        debugger
        addRes.data['door'] = this.formData.addressList[0].door;
        uni.navigateTo({
          url: `/pages/mine/maintenance/payConfirm?data=${encodeURIComponent(JSON.stringify(addRes.data))}`
        });
      } finally {
        this.isPaying = false;
      }
    },
    async handleAutoRenewPay() {
      if (this.autoRenewPaying) return;
      this.autoRenewPaying = true;
      try {
        const userId = uni.getStorageSync('userId');
        const res = await getCardList({ userId });
        if (!res || !res.data || res.data.length === 0) {
          uni.setStorageSync('autoRenewBack', true);
          uni.navigateTo({ url: '/pages/mine/bindCard/index?redirect=maintenance' });
          return;
        }
        const card = res.data[0];

        // 组装订单详情列表
        const orderDetailList = this.formData.addressList.map(addr => {
          return {
            address: addr.fullAddress || '',
            buyCount: addr.months || 1,
            city: Number(addr.city) || 0,
            country: 0,
            deptId: Number(addr.street) || 0,
            district: Number(addr.district) || 0,
            door: addr.door || '',
            houseId: Number(addr.addressId) || 0,
            isPolice: '0',
            name: this.formData.name,
            phone: this.formData.phone,
            province: Number(addr.province) || 0,
            street: Number(addr.street) || 0,
            unitPrice: Number(addr.rate) || 0,
            village: Number(addr.village) || 0,
            type: 1
          };
        });

        const orderParams = {
          chCardNo: card.cardNo,
          chIdNo: card.idNo,
          chMobile: card.mobile,
          chName: card.name,
          landlordName: this.formData.name,
          landlordPhone: this.formData.phone,
          orderDetailList: orderDetailList,
          payChannel: '2',
          openid: uni.getStorageSync('wechat_openid'),
          protocolNo: card.protocolNo,
          remark: `${this.formData.addressList.map(addr => addr.fullAddress).join('；')}`,
          type: 0
        };
        const addRes = await addOrderInfo(orderParams);
        if (!addRes || addRes.code !== 200 || !addRes.data || !addRes.data.orderNo) {
          uni.showToast({ title: addRes.msg || '下单失败', icon: 'none' });
          return;
        }
        // 合并银行卡信息到订单对象，保证字段完整
        const orderData = {
          ...addRes.data,
          chCardNo: card.chCardNo || '',
          chName: card.chName || '',
          chIdNo: card.chIdNo || '',
          chMobile: card.chMobile || '',
          protocolNo: card.protocolNo || '',
          landlordName: this.formData.name,
          landlordPhone: this.formData.phone
        };
        orderData['door'] = this.formData.addressList[0].door;
        uni.navigateTo({
          url: `/pages/mine/maintenance/payConfirm?data=${encodeURIComponent(JSON.stringify(orderData))}&payType=bank`
        });
      } catch (e) {
        console.log(e)
        uni.showToast({ title: '支付失败，请重试', icon: 'none' });
      } finally {
        this.autoRenewPaying = false;
      }
    },
    getIp() {
      // 可用第三方接口或后端返回
      return '';
    },
    async getWechatOpenId() {
      let openid = uni.getStorageSync('wechat_openid');
      console.log('openid', openid);
      if (openid) {
        this.openid = openid;
        return;
      }
      // 只处理公众号H5
      const urlParams = new URLSearchParams(window.location.search);
      const code = urlParams.get('code');
      if (!code) {
        // 没有code，跳转到微信授权页
        const appid = 'wx4636c14a03145741'; // TODO: 替换为你的公众号appid
        const redirectUri = encodeURIComponent(window.location.href);
        const scope = 'snsapi_base'; // 或 snsapi_userinfo
        window.location.href =
          `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=STATE#wechat_redirect`;
        return;
      }
      // 有code，换取openid
      try {
        const res = await request({ url: '/wechat/getOpenId', method: 'get', params: { code } });
        console.log('res', res);
        if (res.code === 200 && res.openid) {
          uni.setStorageSync('wechat_openid', res.openid);
          this.openid = res.openid;
        }
      } catch (e) { }
    },
    getRegisterTime() {
      // 返回注册时间 yyyy-MM-dd HH:mm:ss
      return new Date().toISOString().replace('T', ' ').substring(0, 19);
    },
    genOrderNo() {
      return 'ORDER' + Date.now();
    },
    setMonths(idx, val) {
      this.$set(this.formData.addressList[idx], 'months', val);
    },
    setRate(idx, rate) {
      this.$set(this.formData.addressList[idx], 'rateId', rate.id);
      this.$set(this.formData.addressList[idx], 'rate', rate.price);
      this.$set(this.formData.addressList[idx], 'rateInfo', rate);
    },
    async selectTown(idx) {
      if (!this.formData.addressList[idx].district) { uni.showToast({ title: '请先选择区', icon: 'none' }); return; }
      const province = (this.deptTree[0].children || []).find(p => p.id === this.formData.addressList[idx].province);
      if (!province) return;
      const city = (province.children || []).find(c => c.id === this.formData.addressList[idx].city);
      if (!city) return;
      const district = (city.children || []).find(d => d.id === this.formData.addressList[idx].district);
      if (!district) return;
      const townList = district.children || [];
      const names = townList.map(t => t.label);
      uni.showActionSheet({
        itemList: names,
        success: async ({ tapIndex }) => {
          this.formData.addressList[idx].townName = townList[tapIndex].label;
          this.formData.addressList[idx].townId = townList[tapIndex].id;
          this.formData.addressList[idx].villageName = this.formData.addressList[idx].villageId = '';
          // 查询优惠信息
          const couponInfo = await this.fetchCouponInfo(this.formData.addressList[idx].townId);
          this.$set(this.formData.addressList, idx, {
            ...this.formData.addressList[idx],
            couponInfo
          });
        }
      });
    },
    viewCoupon(idx) {
      const item = this.formData.addressList[idx];
      if (item && item.couponInfo) {
        this.currentCouponInfo = item.couponInfo;
        this.$nextTick(() => {
          this.$refs.couponPopup.open();
        });
      } else {
        this.currentCouponInfo = null;
        this.$nextTick(() => {
          this.$refs.couponPopup.open();
        });
      }
    },
    closePaySuccess() {
      this.showPaySuccess = false;
      // 跳转到详情页或其它页面
      if (this.paySuccessOrderId) {
        uni.redirectTo({ url: `/pages/mine/payment/detail?orderId=${this.paySuccessOrderId}` });
      } else {
        uni.redirectTo({ url: '/pages/mine/account/index' });
      }
    },
    // 拨打客服电话
    callService() {
      uni.showModal({
        title: '拨打客服电话',
        content: '确定拨打客服电话 4006983338 吗？',
        success: (res) => {
          if (res.confirm) {
            uni.makePhoneCall({
              phoneNumber: '4006983338',
              success: () => {
                console.log('拨打客服电话成功');
              },
              fail: (err) => {
                console.error('拨打客服电话失败:', err);
                uni.showToast({
                  title: '拨打失败，请手动拨打',
                  icon: 'none'
                });
              }
            });
          }
        }
      });
    },
    onMonthChange(idx, event) {
      this.formData.addressList[idx].months = event.detail.value;
    },
    goBindCard() {
      // 在这里处理去绑定银行卡的逻辑
      console.log('去绑定银行卡');
      uni.navigateTo({ url: '/pages/mine/bindCard/index' });
    }
  },
  computed: {
    totalPrice() {
      return this.formData.addressList.reduce((sum, item) => {
        const m = Number(item.months), r = Number(item.rate);
        if (!m || !r) return sum;
        return sum + m * r;
      }, 0).toFixed(2);
    },
    maskCardNo() {
      return (cardNo) => {
        return cardNo.replace(/(\d{4})\d{4}(\d{4})/, '$1****$2');
      };
    }
  }
}
</script>

<style lang="scss" scoped>
.maintenance-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-bottom: 120rpx;
}

.info-section {
  background-color: #fff;
  // margin-top: 20rpx; 
  padding: 0 30rpx;
}

.section-title {
  display: flex;
  align-items: center;
  padding: 24rpx 0 16rpx;

  .title-bar {
    width: 6rpx;
    height: 36rpx;
    background-color: #007AFF;
    margin-right: 16rpx;
  }

  .section-title-text {
    font-size: 28rpx;
    font-weight: 500;
    color: #333;
  }
}

.sub-title {
  font-size: 26rpx;
  color: #666;
  padding: 16rpx 0;
}

.input-item {
  display: flex;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 1px solid #f2f2f2;

  .required {
    color: #f56c6c;
    margin-right: 6rpx;
    font-size: 26rpx;
  }

  .label {
    width: 160rpx;
    font-size: 28rpx;
    color: #333;
  }

  .input {
    flex: 1;
    font-size: 28rpx;
  }

  &.arrow-item {
    .right-content {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .placeholder {
        color: #999;
      }

      .arrow {
        font-size: 32rpx;
        color: #999;
        margin-left: 10rpx;
      }
    }
  }
}

.tip-text {
  font-size: 24rpx;
  color: #007AFF;
  padding: 8rpx 0 16rpx 0;
}

.maintenance-info {
  border-top: 10rpx solid #f5f7fa;
  padding-top: 16rpx;
}

.month-select-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 0;

  .month-label {
    font-size: 28rpx;
    color: #333;
  }

  .month-value {
    display: flex;
    align-items: center;

    .month-input {
      width: 160rpx;
      height: 64rpx;
      background-color: #f8f9fa;
      border: none;
      border-radius: 8rpx;
      padding: 0 12rpx;
      margin-right: 8rpx;
      font-size: 28rpx;
      text-align: center;
      color: #333;
      font-weight: bold;
    }
    
    .month-input::placeholder {
      color: #999;
      font-weight: normal;
    }

    .month-unit {
      font-size: 28rpx;
      color: #333;
      margin-left: 8rpx;
    }
  }
}

.month-options {
  display: flex;
  justify-content: space-between;
  padding-bottom: 24rpx;

  .month-btn {
    width: 30%;
    height: 90rpx;
    background-color: #f5f7fa;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 10rpx;
    position: relative;
    font-size: 26rpx;

    &.active {
      background-color: #e6f2ff;
      border: 1px solid #007AFF;
    }

    .recommend-tag {
      position: absolute;
      top: -10rpx;
      right: -10rpx;
      background-color: #ff6b00;
      color: #fff;
      width: 36rpx;
      height: 36rpx;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 22rpx;
    }
  }
}

.coupon-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f0f9ff;
  padding: 16rpx 24rpx;
  border-radius: 10rpx;
  margin-bottom: 24rpx;

  .coupon-info {
    display: flex;
    align-items: center;

    .coupon-icon {
      margin-right: 8rpx;
      color: #007AFF;
    }

    .coupon-text {
      font-size: 24rpx;
      color: #333;
    }
  }

  .coupon-action {
    display: flex;
    align-items: center;

    .view-coupon {
      color: #007AFF;
      font-size: 24rpx;
    }

    .arrow {
      font-size: 28rpx;
      color: #007AFF;
      margin-left: 4rpx;
    }
  }
}

.rate-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 0;
  border-top: 1px solid #f2f2f2;

  .rate-label {
    font-size: 28rpx;
    color: #333;
  }

  .rate-options {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
    padding-bottom: 0;
  }

  .rate-option {
    width: 100%;
    min-height: 88rpx;
    background: #fff;
    border-radius: 24rpx;
    border: 2rpx solid #e5e5e5;
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: relative;
    font-size: 30rpx;
    padding: 28rpx 32rpx 28rpx 32rpx;
    box-sizing: border-box;
    margin-bottom: 0;
    transition: border 0.2s, background 0.2s;
    word-break: break-all;
    white-space: normal;

    .rate-unit {
      color: #888;
      font-size: 30rpx;
      font-weight: 500;
    }

    .rate-amount-wrap {
      display: flex;
      align-items: center;
    }

    .rate-amount {
      font-size: 40rpx;
      color: #333;
      font-weight: bold;
      margin-right: 18rpx;
    }

    .rate-selected {
      color: #1989fa;
      font-weight: bold;
      font-size: 48rpx;
      line-height: 1;
    }

    &.active {
      background: #eaf3ff;
      border: 2rpx solid #1989fa;
    }
  }
}

.add-address-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 24rpx 0;
  color: #007AFF;
  margin: 16rpx 0;
  background-color: #fff;

  .add-icon {
    font-size: 32rpx;
    margin-right: 8rpx;
  }

}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 32rpx;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  height: 110rpx;
  z-index: 10;

  .total-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;

    .total-label {
      font-size: 28rpx;
      color: #666;
      margin-bottom: 6rpx;
    }

    .total-amount-row {
      display: flex;
      align-items: flex-end;
    }

    .total-price {
      font-size: 40rpx;
      color: #f56c6c;
      font-weight: bold;
      margin-right: 6rpx;
    }

    .total-unit {
      font-size: 28rpx;
      color: #f56c6c;
      font-weight: bold;
    }
  }

  .confirm-btn {
    background-color: #1989fa;
    color: #fff;
    padding: 0 56rpx;
    border-radius: 44rpx;
    font-size: 32rpx;
    font-weight: 600;
    height: 80rpx;
    line-height: 80rpx;
    margin-left: 24rpx;
    box-shadow: 0 2rpx 8rpx rgba(25, 137, 250, 0.08);
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.wx-popup-content {
  position: relative; /* 为loading遮罩提供定位基准 */
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
  padding: 0 0 24rpx 0;
  min-height: 60vh;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 -8rpx 32rpx rgba(0, 0, 0, 0.08);
  font-family: "PingFang SC", "Microsoft YaHei", Arial, sans-serif;
}

.wx-popup-tabs {
  display: flex;
  border-bottom: 1px solid #f0f0f0;
}

.wx-tab {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  padding: 28rpx 0 18rpx 0;
  color: #888;
  position: relative;
  cursor: pointer;
}

.wx-tab.active {
  color: #07c160;
  font-weight: bold;
  border-bottom: 4rpx solid #07c160;
  background: #f7f7f7;
}

.wx-popup-header {
  display: flex;
  align-items: center;
  padding: 18rpx 24rpx 0 24rpx;
}

.wx-back-btn {
  margin-right: 12rpx;
  color: #07c160;
  font-size: 36rpx;
  cursor: pointer;
}

.wx-back-arrow {
  font-size: 36rpx;
  color: #07c160;
}

.wx-breadcrumb {
  display: flex;
  flex-wrap: wrap;
}

.wx-breadcrumb-item {
  color: #07c160;
  font-size: 28rpx;
  margin-right: 8rpx;
  cursor: pointer;
}

.wx-breadcrumb-item:after {
  content: "/";
  color: #bbb;
  margin-left: 8rpx;
}

.wx-breadcrumb-item:last-child:after {
  content: "";
}

.wx-popup-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #222;
  padding: 24rpx 24rpx 12rpx 24rpx;
}

.wx-popup-title-sub {
  font-size: 28rpx;
  color: #07c160;
  padding: 12rpx 24rpx 0 24rpx;
}

.wx-popup-title-sub.wx-blue-bar {
  border-left: 8rpx solid #07c160;
  padding-left: 16rpx;
  background: #f7f7f7;
}

.wx-list-wrap {
  padding: 0 24rpx;
}

.wx-list-item {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 16rpx;
  padding: 28rpx 24rpx;
  font-size: 30rpx;
  color: #222;
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  border: 1px solid #f0f0f0;
  transition: background 0.2s, border 0.2s;
}

.wx-list-item.active {
  background: #eafaf1;
  border: 1px solid #07c160;
  color: #07c160;
}

.wx-arrow {
  font-size: 32rpx;
  color: #bbb;
  margin-left: 10rpx;
}

.wx-address-text {
  font-size: 28rpx;
  color: #333;
  word-break: break-all;
}

/* 全局Loading样式 */
.global-loading-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  border-radius: 24rpx 24rpx 0 0;
}

.global-loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40rpx;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.global-loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #07c160;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20rpx;
}

.global-loading-text {
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.wx-popup-title-sub.wx-blue-bar {
  position: relative;
  padding-left: 20rpx;
}

.wx-popup-title-sub.wx-blue-bar::before {
  content: '';
  display: inline-block;
  width: 6rpx;
  height: 24rpx;
  background-color: #007AFF;
  border-radius: 3rpx;
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
}

.wx-landlord-switch {
  display: flex;
  align-items: center;
  gap: 16rpx;
  padding: 0 36rpx 16rpx 36rpx;
}

.wx-search-input {
  padding: 0 36rpx 16rpx 36rpx;
}

.close-icon {
  font-size: 32rpx;
  color: #999;
  margin-left: auto;
  cursor: pointer;
  padding: 8rpx;
}

.no-address-tip {
  color: #f56c6c;
  font-size: 24rpx;
  margin: 10rpx 0 0 30rpx;

  .phone {
    color: #007AFF;
  }
}

.address-ellipsis {
  white-space: normal !important;
  word-break: break-all;
  overflow: visible;
  text-overflow: initial;
  display: block;
  max-width: 100%;
}

.edit-btn {
  color: #007AFF;
  font-size: 26rpx;
  margin-left: 18rpx;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
  background: #f5f7fa;
}

.pay-success-popup {
  background: #fff;
  border-radius: 24rpx;
  padding: 48rpx 36rpx 32rpx 36rpx;
  text-align: center;

  .pay-success-icon {
    width: 80rpx;
    height: 80rpx;
    margin: 0 auto 24rpx auto;
    // background: url('/static/images/success-green.png') no-repeat center/contain;
    // 如无图片可用SVG
    display: inline-block;
  }

  .pay-success-title {
    font-size: 36rpx;
    color: #07c160;
    font-weight: bold;
    margin-bottom: 12rpx;
  }

  .pay-success-desc {
    font-size: 28rpx;
    color: #888;
    margin-bottom: 32rpx;
  }

  .pay-success-btn {
    background: #07c160;
    color: #fff;
    border-radius: 44rpx;
    font-size: 30rpx;
    padding: 18rpx 0;
    width: 100%;
    border: none;
  }
}

.auto-renew-popup {
  background: #fff;
  border-radius: 24rpx;
  padding: 48rpx 36rpx 32rpx 36rpx;
  text-align: center;
  min-width: 480rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.10);

  .title {
    font-size: 34rpx;
    color: #222;
    font-weight: bold;
    margin-bottom: 36rpx;
    letter-spacing: 1rpx;
  }

  .desc {
    font-size: 28rpx;
    color: #888;
    margin-bottom: 40rpx;
    line-height: 1.6;
  }

  .btn-group {
    display: flex;
    gap: 24rpx;
    margin-top: 12rpx;

    button {
      flex: 1;
      font-size: 30rpx;
      border-radius: 44rpx;
      padding: 20rpx 0;
      border: none;
      transition: background 0.2s, color 0.2s;
      font-weight: 500;
      background: #f5f7fa;
      color: #333;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
    }

    .primary {
      background: linear-gradient(90deg, #07c160 0%, #34d399 100%);
      color: #fff;
      font-weight: bold;
      box-shadow: 0 4rpx 16rpx rgba(7, 193, 96, 0.10);
    }

    .cancel {
      background: #f5f7fa;
      color: #888;
    }
  }
}

.encrypt-preview {
  color: #888;
  font-size: 24rpx;
  margin-left: 12rpx;
}

.multi-address-tip-fixed {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 110rpx; // 位于footer上方
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fffbe6;
  padding: 12rpx 0;
  z-index: 11;
  border-top: 1px solid #ffe58f;

  .tip-icon {
    font-size: 24rpx;
    color: #ff9800;
    margin-right: 8rpx;
  }

  .tip-text {
    font-size: 24rpx;
    color: #ff9800;
  }
}

.coupon-detail-popup {
  background: #fff;
  border-radius: 24rpx;
  width: 640rpx;
  max-width: 90vw;
  max-height: 80vh;
  overflow: hidden;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.15);
  
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1px solid #f2f2f2;
    background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
    
    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .close-icon {
      font-size: 36rpx;
      color: #999;
      padding: 10rpx;
      border-radius: 50%;
      background: #f5f5f5;
      
      &:active {
        background: #e5e5e5;
      }
    }
  }
  
  .coupon-content {
    padding: 0;
    max-height: 60vh;
    overflow-y: auto;
  }
  
  // 各个区域的通用样式
  .price-info-section, .rules-section, .price-list-section, .instruction-section {
    padding: 24rpx 30rpx;
    border-bottom: 1px solid #f8f9fa;
    
    &:last-child {
      border-bottom: none;
    }
  }
  
  .section-title {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    
    .section-icon {
      font-size: 32rpx;
      margin-right: 12rpx;
    }
    
    .section-text {
      font-size: 30rpx;
      font-weight: 600;
      color: #333;
    }
  }
  
  // 价格信息样式
  .info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16rpx 0;
    border-bottom: 1px solid #f5f5f5;
    
    &:last-child {
      border-bottom: none;
    }
    
    .info-label {
      font-size: 28rpx;
      color: #666;
    }
    
    .info-value {
      font-size: 28rpx;
      font-weight: 600;
      color: #333;
      
      &.highlight {
        color: #ff6b00;
        font-weight: bold;
      }
    }
  }
  
  // 优惠规则样式
  .coupon-rule-item {
    margin-bottom: 20rpx;
    padding: 20rpx;
    background: #f8f9fa;
    border-radius: 12rpx;
    border-left: 4rpx solid #ff6b00;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .rule-header {
      display: flex;
      align-items: center;
      margin-bottom: 12rpx;
      
      .rule-tag {
        background: linear-gradient(135deg, #ff6b00 0%, #ff8533 100%);
        color: #fff;
        padding: 4rpx 12rpx;
        border-radius: 12rpx;
        font-size: 22rpx;
        margin-right: 12rpx;
        flex-shrink: 0;
        font-weight: 600;
      }
      
      .rule-title {
        font-size: 28rpx;
        color: #333;
        font-weight: 600;
        flex: 1;
      }
    }
    
    .rule-details {
      display: flex;
      gap: 16rpx;
      margin-bottom: 8rpx;
      
      .rule-detail {
        font-size: 24rpx;
        color: #666;
        background: #ffffff;
        padding: 6rpx 12rpx;
        border-radius: 8rpx;
        border: 1px solid #e5e5e5;
      }
    }
    
    .rule-description {
      font-size: 24rpx;
      color: #888;
      line-height: 1.4;
      margin-top: 8rpx;
    }
  }
  
  // 运维费档位样式
  .price-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16rpx 20rpx;
    margin-bottom: 12rpx;
    background: #f8f9fa;
    border-radius: 12rpx;
    border: 1px solid #e5e5e5;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .price-label {
      font-size: 28rpx;
      color: #333;
    }
    
    .price-amount {
      font-size: 28rpx;
      font-weight: 600;
      color: #1989fa;
    }
  }
  
  // 说明信息样式
  .instruction-text {
    font-size: 26rpx;
    color: #666;
    line-height: 1.5;
    padding: 16rpx 20rpx;
    background: #f0f9ff;
    border-radius: 12rpx;
    border-left: 4rpx solid #1989fa;
  }
  
  // 无优惠信息样式
  .no-coupon {
    text-align: center;
    padding: 60rpx 30rpx;
    
    .no-coupon-icon {
      font-size: 80rpx;
      margin-bottom: 20rpx;
      display: block;
    }
    
    .no-coupon-text {
      color: #999;
      font-size: 28rpx;
    }
  }
}

.no-address-tip {
  background: linear-gradient(135deg, #fff5f5 0%, #fff0f0 100%);
  border: 1px solid #ffebeb;
  border-radius: 12rpx;
  padding: 24rpx;
  margin: 16rpx 24rpx;
  text-align: center;
  
  .no-address-content {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 12rpx;
    
    .no-address-text {
      color: #ff6b6b;
      font-size: 28rpx;
      font-weight: 500;
      margin-left: 8rpx;
    }
  }
  
  .contact-info {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;
    
    .contact-label {
      color: #666;
      font-size: 26rpx;
      margin-right: 8rpx;
    }
    
    .phone-number {
      color: #1989fa;
      font-size: 28rpx;
      font-weight: bold;
      text-decoration: underline;
      padding: 4rpx 8rpx;
      border-radius: 6rpx;
      background-color: rgba(25, 137, 250, 0.1);
      
      &:active {
        background-color: rgba(25, 137, 250, 0.2);
      }
    }
  }
}

/* 无障碍可读性增强：选择地址弹窗字体适度放大，便于中老年用户阅读 */
.wx-popup-title {
  font-size: 36rpx !important;
}

.wx-breadcrumb-item {
  font-size: 30rpx !important;
}

.wx-back-arrow {
  font-size: 40rpx !important;
}

.wx-tab {
  font-size: 34rpx !important;
}

.wx-popup-title-sub {
  font-size: 32rpx !important;
}

/* 列表项整体放大行高与内边距 */
.wx-list-item {
  font-size: 32rpx !important;
  min-height: 72rpx !important;
  padding: 12rpx 16rpx !important;
}

.wx-arrow {
  font-size: 36rpx !important;
}

/* 地址文本放大 */
.wx-address-text {
  font-size: 30rpx !important;
}

.wx-search-tip {
  color: #999;
  font-size: 24rpx;
  margin-bottom: 12rpx;
  text-align: center;
}

/* 添加搜索输入框样式 */
.wx-search-input {
  padding: 0 32rpx 16rpx 32rpx;
}

.search-input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  border: 1px solid #e9ecef;
  border-radius: 24rpx;
  padding: 20rpx 24rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.search-input-wrapper:focus-within {
  border-color: #07c160;
  box-shadow: 0 4rpx 12rpx rgba(7, 193, 96, 0.15);
  background: linear-gradient(135deg, #f0fff4 0%, #ffffff 100%);
}

.house-search-input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  background: transparent;
  border: none;
  outline: none;
  margin-left: 16rpx;
  line-height: 1.4;
}

.house-search-input::placeholder {
  color: #999;
  font-size: 26rpx;
}

.house-search-input:focus {
  color: #07c160;
}

.clear-btn {
  width: 36rpx;
  height: 36rpx;
  background: linear-gradient(135deg, #ff6b6b 0%, #ff5252 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 22rpx;
  font-weight: bold;
  margin-left: 16rpx;
  cursor: pointer;
  transition: all 0.2s ease;
  box-shadow: 0 2rpx 6rpx rgba(255, 107, 107, 0.3);
}

.clear-btn:active {
  transform: scale(0.9);
  box-shadow: 0 1rpx 4rpx rgba(255, 107, 107, 0.4);
}



.bank-card-popup {
  background: #fff;
  border-radius: 24rpx;
  padding: 48rpx 36rpx 32rpx 36rpx;
  text-align: center;
  min-width: 480rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.10);

  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1px solid #f2f2f2;
    
    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .close-icon {
      font-size: 36rpx;
      color: #999;
      padding: 10rpx;
    }
  }
  
  .bank-card-content {
    padding: 30rpx;
    max-height: 60vh;
    overflow-y: auto;
  }
  
  .card-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    margin-bottom: 24rpx;
  }
  
  .card-item {
    width: 48%;
    background: #f5f7fa;
    border-radius: 12rpx;
    padding: 16rpx;
    margin-bottom: 16rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: pointer;
    transition: background 0.2s;
    

    
    .card-info {
      display: flex;
      flex-direction: column;
      
      .bank-name {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 8rpx;
      }
      
      .card-no {
        font-size: 26rpx;
        color: #666;
      }
    }
    
    .card-selected {
      font-size: 32rpx;
      color: #1989fa;
      font-weight: bold;
    }
  }
  
  .no-card-tip {
    text-align: center;
    color: #999;
    font-size: 28rpx;
    padding: 40rpx 0;
  }
  
  .bind-card-btn {
    background: #07c160;
    color: #fff;
    border-radius: 44rpx;
    font-size: 30rpx;
    padding: 18rpx 0;
    width: 100%;
    border: none;
    margin-top: 24rpx;
  }
  
  .popup-footer {
    display: flex;
    justify-content: center;
    margin-top: 24rpx;
    
    .confirm-btn {
      background: #1989fa;
      color: #fff;
      border-radius: 44rpx;
      font-size: 32rpx;
      padding: 18rpx 0;
      width: 100%;
      border: none;
    }
  }
}
</style>
